import React, { useEffect, useRef, useState } from 'react';
import { Chart } from '@antv/g2';
import { productExchange } from "../../../api/axios8081";

interface ChartData {
  selldate: string;
  sellNum: number;
}

interface LineChartProps {
  beginTime?: string;
  endTime?: string;
}

const LineChart: React.FC<LineChartProps> = ({ beginTime, endTime }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const [chartData, setChartData] = useState<ChartData[]>([]);
  console.log(beginTime, endTime, '这是一个时间')
  useEffect(() => {
    // 获取数据的effect  
    const fetchData = async () => {
      try {
        console.log(99999)
        const response = await productExchange(beginTime, endTime);
        console.log(response, '让我看看怎么回事')
        console.log(response.data, '让我看看怎么回事01')
        const data: ChartData[] = response.data.map((item: { sellDate: string; sellNum: number; }) => ({
          selldate: item.sellDate,
          sellNum: item.sellNum
        }));
        data.sort((a, b) => {
          return a.selldate.localeCompare(b.selldate);
        });

        console.log(response.data, '这是response.data')
        console.log(data, '这是data')
        setChartData(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, []); // 只在组件挂载时运行一次  

  useEffect(() => {
    if (chartRef.current && chartData.length > 0) {
      const chart = new Chart({
        container: chartRef.current,
        autoFit: true,
        height: 500, 
      });

     
      chart.data(chartData);
      chart.scale('x', {
        range: [0, 1],
        tickCount: 5,  
      });
      chart.scale('y', {
        nice: true,
      });
      chart.axis('x', {
        title: '日期',

        tickLine: null,
      });
      chart.axis('y', {
        title: '销售量',
        city: '日期',
      });

      chart.encode('x', 'selldate');
      chart.encode('y', 'sellNum');


      chart.line().label({
        text: 'sellNum',
        style: {
          dx: -10,
          dy: -12,
        },
      });

      chart.point().style('fill', 'white').tooltip(false);


      chart.render();

      // 清理函数
      return () => {
        chart.destroy();
      };
    }
  }, [chartData]); // 当chartData状态更新时，这个effect会重新运行  

  return <div ref={chartRef} />;
};

export default LineChart;